<!-- selectwarehouse.vue -->
<script setup>
import { ref, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import selectgoods from '@/views/stocktaking/info/selectgoods.vue'
import { addApi } from '@/api/stocktaking/info'


// 获取仓库、库区、库位数据
import { getInfoApi as getWarehouseApi } from '@/api/warehouse/warehouse'
import { getAreaInfoApi as getWarehouseAreaApi } from '@/api/warehouse/warehouseArea'
import { getAreaLocalInfoApi as getWarehouseAreaLocalApi } from '@/api/warehouse/warehouseAreaLocal'


const emit = defineEmits(['confirm', 'cancel'])

const dialogVisible = ref(false)
const warehouseOptions = ref([])
const areaOptions = ref([])
const locationOptions = ref([])
const selectGoodRef = ref(null)

// 表单数据
const formData = ref({
  tartgetWarehouseId: '',
  tartgetWarehouseAreaId: '',
  tartgetWarehouseAreaLocaId: '',
  skuId: '',
  bookCount: '',
  correctCount: '',
  discrepancyCount: '',
  category: '',
})

// 商品详情
const goodsInfo = ref({
  tartgetWarehouseId: '',
  tartgetWarehouseAreaId: '',
  tartgetWarehouseAreaLocaId: '',
  code: '',
  name: '',
  specCode: '',
  sn: '',
  warehouseName: '',
  locationCode: '',
  price: 0,
  expireDate: '',
  shelfDate: '',
  bookCount: 0
})


// 是否显示选择库存弹窗
const showSelectGoods = ref(false)

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const res = await getWarehouseApi()
    warehouseOptions.value = res.map(item => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    ElMessage.error('获取仓库失败')
  }
}

// 根据仓库ID获取库区
const fetchAreas = async (warehouseId) => {
  if (!warehouseId) return
  try {
    const res = await getWarehouseAreaApi(warehouseId)
    areaOptions.value = res.map(item => ({
      value: item.id,
      label: item.name
    }))
    locationOptions.value = []
    formData.value.areaId = null
    formData.value.locationId = null
  } catch (error) {
    ElMessage.error('获取库区失败')
  }
}

// 根据库区ID获取库位
const fetchLocations = async (areaId) => {
  if (!areaId) return
  try {
    const res = await getWarehouseAreaLocalApi(areaId)
    locationOptions.value = res.map(item => ({
      value: item.id,
      label: item.name
    }))
    formData.value.locationId = null
  } catch (error) {
    ElMessage.error('获取库位失败')
  }
}

// 监听仓库变化
watch(() => formData.value.warehouseId, (newVal) => {
  if (newVal) {
    fetchAreas(newVal)
  }
})

// 监听库区变化
watch(() => formData.value.areaId, (newVal) => {
  if (newVal) {
    fetchLocations(newVal)
  }
})

// 打开弹窗
const open = () => {
  dialogVisible.value = true
  fetchWarehouses()
}

// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  formData.value = { warehouseId: null, areaId: null, locationId: null }
  goodsInfo.value = {}
}

// 选择库存
const selectGoods = () => {
  selectGoodRef.value.open()
}
// 处理选中的商品
const handleGoodsSelected = (selectedGoods) => {
  // 这里处理选中的商品数据
  // 可以选择第一个商品作为显示信息，或者根据实际需求处理
  if (selectedGoods && selectedGoods.length > 0) {
    const firstGood = selectedGoods[0]
    goodsInfo.value = {
      tartgetWarehouseId: firstGood.warehouseId || '',
      tartgetWarehouseAreaId: firstGood.warehouseAreaId || '',
      tartgetWarehouseAreaLocaId: firstGood.warehouseAreaLocaId || '',
      code: firstGood.skuCode || '',
      name: firstGood.skuTitle || '',
      skuId: firstGood.skuId,
      specCode: firstGood.skuCode || '',
      sn: firstGood.sn || '',
      warehouseName: firstGood.warehouseName || '',
      locationCode: firstGood.warehouseAreaLocaLocaCode || '',
      price: firstGood.price || 0,
      expireDate: firstGood.expireDate || '',
      shelfDate: firstGood.createTime || '',
      bookCount: firstGood.count || 0
    }
    formData.value = {
      targetWarehouseId: firstGood.warehouseId || '',
      targetWarehouseAreaId: firstGood.warehouseAreaId || '',
      targetWarehouseAreaLocaId: firstGood.warehouseAreaLocaId || '',
      skuId: firstGood.skuId,
      bookCount: firstGood.count,
      correctCount: 0,
      discrepancyCount: 0,
      category: 1,
      status: 1
    }
    console.log('formData', formData)
    console.log('goodsInfo', goodsInfo)
  }
}

// 确认提交
const confirm = async () => {
  if (!formData) {
    ElMessage.error('请选择完整的仓库信息')
    return
  }
  let res = await addApi(formData.value)
  if (res.code) {
    ElMessage.success('操作成功！')
    emit('refresh')
  } else {
    ElMessage.error('操作失败!')
  }
  close()
}

// 取消
const cancel = () => {
  emit('cancel')
  close()
}

defineExpose({
  open,
  close
})
</script>

<template>
  <selectgoods ref="selectGoodRef" @confirm="handleGoodsSelected" />
  <el-dialog v-model="dialogVisible" title="库存盘点" width="600px" :close-on-click-modal="false">
    <!-- 顶部操作按钮 -->
    <div class="top-actions">
      <el-button size="small" @click="selectGoods">选择库存</el-button>
      <el-button size="small" type="primary" @click="confirm">提交</el-button>
    </div>

    <!-- 商品详情 -->
    <div class="goods-detail">
      <div class="item">
        <label>商品编码</label>
        <div class="value">{{ goodsInfo.code }}</div>
      </div>
      <div class="item">
        <label>商品名称</label>
        <div class="value">{{ goodsInfo.name }}</div>
      </div>
      <div class="item">
        <label>规格编码</label>
        <div class="value">{{ goodsInfo.specCode }}</div>
      </div>
      <div class="item">
        <label>序列号</label>
        <div class="value">{{ goodsInfo.sn || '无' }}</div>
      </div>
      <div class="item">
        <label>所在仓库</label>
        <div class="value">{{ goodsInfo.warehouseName }}</div>
      </div>
      <div class="item">
        <label>所在库位</label>
        <div class="value">{{ goodsInfo.locationCode }}</div>
      </div>
      <div class="item">
        <label>商品价格</label>
        <div class="value">{{ goodsInfo.price }}</div>
      </div>
      <div class="item">
        <label>过期日期</label>
        <div class="value">{{ goodsInfo.expireDate || '无' }}</div>
      </div>
      <div class="item">
        <label>上架日期</label>
        <div class="value">{{ goodsInfo.shelfDate }}</div>
      </div>
      <div class="item">
        <label>账面数量</label>
        <div class="value">{{ goodsInfo.bookCount }}</div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="confirm">提交</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.top-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.goods-detail {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.item {
  margin-bottom: 15px;
}

.item label {
  display: block;
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.item .value {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: white;
  min-height: 32px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>